package cn.lxb.netstatagent;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;

public class FileRecorder implements AddressRecorder {
	static String filePath = System.getProperty("netstat-agent.file.path");
	static String maxSizeStr = System.getProperty("netstat-agent.file.max-size"); // 10M

	@Override
	public void record(String address) throws Exception {
		LogUtil.debug("记录到文件:" + address + ", filePath=" + filePath);
		int maxSize = Integer.parseInt(maxSizeStr) * 1024;
		Path path = Paths.get(filePath);
		int fileSize = (int) Files.size(path);
		if (fileSize > maxSize) {
			LogUtil.error("文件大小已超过限制!!!maxSize=" + maxSize);
			return;
		}
		try (Stream<String> stream = Files.lines(path)) {
			if (stream.noneMatch(address::equals)) {
				Files.write(path, (address + System.lineSeparator()).getBytes(), StandardOpenOption.APPEND);
			}
		}
	}

}
